#include "GameScene.h"

USING_NS_CC;



#define PTM_RATIO 32.0
#define TAG_PARALLAX 5
/*
#define CHAR_IDLE 			0
#define CHAR_READY 			1
#define CHAR_READY_END		2
#define CHAR_RUN			3
#define CHAR_WALK			4
#define CHAR_BREATH			5
#define CHAR_BREATH_END		6
#define CHAR_FALLDOWN		7
#define CHAR_FALLDOWN_END	8
#define CHAR_RUNJUMP		9
#define CHAR_RUNJUMP_END	10
 */


CCScene* GameScene::scene()
{
	// 'scene' is an autorelease object
	CCScene *scene = CCScene::create();

	// 'layer' is an autorelease object
	GameScene *layer = GameScene::create();

	// add layer as a child to scene
	scene->addChild(layer);

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
bool GameScene::init()
{
	//////////////////////////////
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}
	this->setTouchEnabled(true);

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	/////////////////////////////
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//    you may modify it.

	// add a "close" icon to exit the progress. it's an autorelease object
	CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
			"CloseNormal.png",
			"CloseSelected.png",
			this,
			menu_selector(GameScene::menuCloseCallback));

	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
			origin.y + pCloseItem->getContentSize().height/2));

	CCLabelTTF* lableTTF = CCLabelTTF::create("run", "Arial", 50);
	CCMenuItemLabel* menurun = CCMenuItemLabel::create(lableTTF,this,menu_selector(GameScene::runCharacter));
	menurun->setPosition(ccp(winSize.width - lableTTF->getContentSize().width - 50,600));

	lableTTF = CCLabelTTF::create("fall down", "Arial", 50);
	CCMenuItemLabel* menudown = CCMenuItemLabel::create(lableTTF,this,menu_selector(GameScene::falldownCharacter));
	menudown->setPosition(ccp(winSize.width - lableTTF->getContentSize().width - 50,500));
	lableTTF = CCLabelTTF::create("fall down pre", "Arial", 50);
	CCMenuItemLabel* menudownpre = CCMenuItemLabel::create(lableTTF,this,menu_selector(GameScene::falldownpreCharacter));
	menudownpre->setPosition(ccp(winSize.width - lableTTF->getContentSize().width - 50,400));



	// create menu, it's an autorelease object
	CCMenu* pMenu = CCMenu::create(pCloseItem, menurun, menudown, menudownpre, NULL);
	pMenu->setPosition(CCPointZero);
	this->addChild(pMenu, 1);

	/////////////////////////////
	// 3. add your codes below...

	// add a label shows "Hello World"
	// create and initialize a label

	// Define the gravity vector.
	b2Vec2 gravity;
	gravity.Set(0.0f, -9.0f);

	// Do we want to let bodies sleep?
	bool doSleep = true;

	// Construct a world object, which will hold and simulate the rigid bodies.
	_world = new b2World(gravity);

	// Create edges around the entire screen
	// Define the ground body.
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set(0, 0); // bottom-left corner

	// Call the body factory which allocates memory for the ground body
	// from a pool and creates the ground box shape (also from a pool).
	// The body is also added to the world.
	_groundBody = _world->CreateBody(&groundBodyDef);



	float widthInMeters = winSize.width / PTM_RATIO;
	float heightInMeters = winSize.height / PTM_RATIO;
	b2Vec2 lowerLeftCorner = b2Vec2(0, 0);
	b2Vec2 lowerRightCorner = b2Vec2(widthInMeters, 0);
	b2Vec2 upperLeftCorner = b2Vec2(0, heightInMeters);
	b2Vec2 upperRightCorner = b2Vec2(widthInMeters, heightInMeters);

	b2EdgeShape screenBorderShape;

	// Create fixtures for the four borders (the border shape is re-used)
	screenBorderShape.Set(lowerLeftCorner, lowerRightCorner);
	_bottomFixture = _groundBody->CreateFixture(&screenBorderShape, 0);
	screenBorderShape.Set(lowerRightCorner, upperRightCorner);
	_groundBody->CreateFixture(&screenBorderShape, 0);
	screenBorderShape.Set(upperRightCorner, upperLeftCorner);
	_groundBody->CreateFixture(&screenBorderShape, 0);
	screenBorderShape.Set(upperLeftCorner, lowerLeftCorner);
	_groundBody->CreateFixture(&screenBorderShape, 0);



	_dist = 0;
	_dist2 = 0;
	_dist3 = 0;

	CCSprite* back_s = CCSprite::create("back1_s.jpg");
	back_s->setAnchorPoint(ccp(0,0));
	back_s->setPosition(ccp(0,winSize.height - back_s->getContentSize().height));

	this->addChild(back_s);

	_p1 = CCLabelTTF::create("You", "Arial", 12);
	_p2 = CCLabelTTF::create("Op", "Arial", 12);
	_p3 = CCLabelTTF::create("Op2", "Arial", 12);

	_p1->setColor(ccc3(0, 0, 255));
	_p2->setColor(ccc3(255, 0, 0));
	_p3->setColor(ccc3(0, 255, 0));

	_p1->setPosition(ccp(0, back_s->getPosition().y + 20));
	_p2->setPosition(ccp(0, back_s->getPosition().y + 30));
	_p2->setPosition(ccp(0, back_s->getPosition().y + 40));


	this->addChild(_p3);
	this->addChild(_p2);
		this->addChild(_p1);


	CCSprite* background1 = CCSprite::create("back1.jpg");
	background1->setAnchorPoint(ccp(0,0));
	background1->setPosition(ccp(0,0));

	CCSprite* background2 = CCSprite::create("back1.jpg");
	background2->setAnchorPoint(ccp(0,0));
	background2->setPosition(ccp(background1->getContentSize().width,0));


	background1->setTag(5);
	background2->setTag(6);

	this->addChild(background1);
	this->addChild(background2);

	/*
	CCSprite* background1 = CCSprite::create("back1.jpg");
	background1->setAnchorPoint(ccp(0,0));
	background1->setPosition(ccp(0,500));

	CCSprite* background2 = CCSprite::create("back1.jpg");
	background2->setAnchorPoint(ccp(0,0));
	background2->setPosition(ccp(background1->getContentSize().width,500));


	background1->setTag(7);
	background2->setTag(8);

	this->addChild(background1);
	this->addChild(background2);


	_s1 = CHAR_IDLE;
	_s2 = CHAR_IDLE;
	 */
	_speed = 0;
	_speed2 = 0;
	_speed3 = 0;



	extension::CCArmatureDataManager::sharedArmatureDataManager()
	->addArmatureFileInfo("bros0.png", "bros0.plist", "bros.ExportJson");//, this, NULL/*schedule_selector(TestArmatureNesting::close)*/);

	extension::CCArmatureDataManager::sharedArmatureDataManager()
	->addArmatureFileInfo("bros20.png", "bros20.plist", "bros2.ExportJson");//, this, NULL/*schedule_selector(TestArmatureNesting::close)*/);



	_user = new GameUser(OT_USER);
	_user->init();

	_user->armature = cocos2d::extension::CCArmature::create("bros2");

	_user->armature->setPosition(ccp(300,130));
	_user->armature->setScale(1.0f);

	this->addChild(_user->armature, 99);

	_user->status = CHAR_READY_START;



	_op = new GameUser(OT_USER);
	_op->init();

	_op->armature = cocos2d::extension::CCArmature::create("bros");

	_op->armature->setPosition(ccp(250,250));
	_op->armature->setScale(0.9f);

	this->addChild(_op->armature);

	_op->status = CHAR_READY_START;



	_op2 = new GameUser(OT_USER);
	_op2->init();

	_op2->armature = cocos2d::extension::CCArmature::create("bros");

	_op2->armature->setPosition(ccp(350,10));
	_op2->armature->setScale(1.1f);

	this->addChild(_op2->armature, 100);

	_op2->status = CHAR_READY_START;


	/*
	CCParticleSystem* pParticle = CCParticleFire::create();
	pParticle->setPositionX(100);
	pParticle->setPositionY(100);
	this->addChild(pParticle, 0);


	armature2 = cocos2d::extension::CCArmature::create("bros");

	armature2->getAnimation()->playByIndex(4);
	armature2->setPosition(ccp(350,250));
	armature2->setScale(0.9f);
	armature2->getAnimation()->setSpeedScale(1.0f);

	this->addChild(armature2);
	this->addChild(armature);

	_s1 = CHAR_READY;
	_s2 = CHAR_READY;

	 */
	_sp = CCLabelBMFont::create("asdf", "testfont.fnt");
	_sp->setColor(ccc3(255, 255, 255));

	_sp->setPosition(ccp(300, 500));

	this->addChild(_sp, 1000);






	/*
	CCParallaxNode* paraNode = CCParallaxNode::create();

	CCSprite* background1 = CCSprite::create("back1.jpg");
		background1->setAnchorPoint(ccp(0,0));

		CCSprite* background2 = CCSprite::create("back1.jpg");
			background2->setAnchorPoint(ccp(0,0));


	    paraNode->addChild(background1, 0, ccp(1.0, 1.0), ccp(0,300));
	    paraNode->addChild(background2, 1, ccp(2.0, 2.0), ccp(0,0));

	    paraNode->setTag(TAG_PARALLAX);

	    CCActionInterval* go = CCMoveBy::create(4, ccp(-1024, 0));
	    	CCActionInterval* goBack = go->reverse();
	    	CCFiniteTimeAction* seq = CCSequence::create(go, goBack, NULL);
	    	CCAction* act = CCRepeatForever::create((CCActionInterval*)seq);

	    	paraNode->runAction(act);
	    	this->addChild(paraNode);

	 */






	/*

	CCSprite *projectile = CCSprite::create("CloseNormal.png",
			CCRectMake(0, 0, 20, 20));

	projectile->setPosition(ccp(100, 100));
	projectile->setTag(1);
	this->addChild(projectile);


	b2BodyDef ballBodyDef;
	ballBodyDef.type = b2_dynamicBody;
	ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
	ballBodyDef.userData = projectile;

	b2Body *ballBody = _world->CreateBody(&ballBodyDef);

	// Create circle shape
	b2CircleShape circle;
	circle.m_radius = 20.0/PTM_RATIO;

	// Create shape definition and add body
	b2FixtureDef ballShapeDef;
	ballShapeDef.shape = &circle;
	ballShapeDef.density = 1.0f;
	ballShapeDef.friction = 1.0f;
	ballShapeDef.restitution = 0.8f;

	_ballFixture = ballBody->CreateFixture(&ballShapeDef);

	//b2Vec2 force = b2Vec2(10, 10);
	//ballBody->ApplyLinearImpulse(force,  _groundBody->GetWorldCenter());//ballBodyDef.position);
	ballBody->SetLinearDamping(0.3);



	for(int i = 0; i < 4; i++) {

		static int padding=50;

		// Create block and add it to the layer
		CCSprite *block = CCSprite::create("CloseNormal.png");
		int xOffset = 100+ padding+block->getContentSize().width/2+
				((block->getContentSize().width+padding)*i);
		block->setPosition(ccp(xOffset/PTM_RATIO, 250/PTM_RATIO));
		block->setTag(2);
		this->addChild(block);

		// Create block body
		b2BodyDef blockBodyDef;
		blockBodyDef.type = b2_staticBody;
		blockBodyDef.position.Set(xOffset/PTM_RATIO, 250/PTM_RATIO);
		blockBodyDef.userData = block;
		b2Body *blockBody = _world->CreateBody(&blockBodyDef);

		// Create block shape
		b2PolygonShape blockShape;
		blockShape.SetAsBox(block->getContentSize().width/PTM_RATIO/2,
				block->getContentSize().height/PTM_RATIO/2);

		// Create shape definition and add to body
		b2FixtureDef blockShapeDef;
		blockShapeDef.shape = &blockShape;
		blockShapeDef.density = 1.0;
		blockShapeDef.friction = 0.0;
		blockShapeDef.restitution = 0.1f;
		blockBody->CreateFixture(&blockShapeDef);

		blockBody->SetAngularVelocity(1);
	}


	Vector2dVector a;

	a.push_back( Vector2d(0,0));
	a.push_back( Vector2d(200,0));
	a.push_back( Vector2d(200,200));
	a.push_back( Vector2d(0,200));
	a.push_back( Vector2d(0,50));

	CCTexture2D *texture =  CCTextureCache::sharedTextureCache()->addImage("basket.png");

	if( texture == NULL ) {
		CCLOG("texture null--------------------");
	}
	PRFilledPolygon *filledPolygon = PRFilledPolygon::filledPolygonWithPointsAndTexture(a,texture);



	//CCSprite *filledPolygon = CCSprite::create("basket.png");



	filledPolygon->setPosition(ccp(600.0f/PTM_RATIO,100.0f/PTM_RATIO));

	filledPolygon->setTag(2);

	this->addChild(filledPolygon);
	 */
	//	{
	//		b2BodyDef blockBodyDef;
	//		blockBodyDef.type = b2_dynamicBody;
	//		blockBodyDef.position.Set(600.0f/PTM_RATIO, 100.0f/PTM_RATIO);
	//		blockBodyDef.userData = filledPolygon;
	//		b2Body *blockBody2 = _world->CreateBody(&blockBodyDef);
	//
	//		// Create block shape
	//
	//		b2Vec2 vertices[16];
	//		/*
	//		vertices[0].Set(-69.000f/PTM_RATIO,73.000f/PTM_RATIO);
	//		vertices[1].Set( -55.000f/PTM_RATIO,73.000f/PTM_RATIO );
	//		vertices[2].Set( -50.000f/PTM_RATIO,-48.000f/PTM_RATIO );
	//		vertices[3].Set( 2.000f/PTM_RATIO,-48.000f/PTM_RATIO );
	//		vertices[4].Set( -1.000f/PTM_RATIO,12.000f/PTM_RATIO );
	//		vertices[5].Set( 26.000f/PTM_RATIO,59.000f/PTM_RATIO );
	//		vertices[6].Set( 27.000f/PTM_RATIO,75.000f/PTM_RATIO );
	//		vertices[7].Set( 39.000f/PTM_RATIO,79.000f/PTM_RATIO );
	//		vertices[8].Set( 42.000f/PTM_RATIO,54.000f/PTM_RATIO );
	//		vertices[9].Set( 15.000f/PTM_RATIO,05.000f/PTM_RATIO );
	//		vertices[10].Set( 20.000f/PTM_RATIO,-36.000f/PTM_RATIO );
	//		vertices[11].Set( 11.000f/PTM_RATIO,-63.000f/PTM_RATIO );
	//		vertices[12].Set( -62.000f/PTM_RATIO,-63.000f/PTM_RATIO );
	//		vertices[13].Set( -69.000f/PTM_RATIO,73.000f/PTM_RATIO );
	//		 */
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//
	//		int32 count = 10;
	//
	//		b2PolygonShape shape;
	//		b2FixtureDef blockShapeDef;
	//
	//		vertices[0].Set( 45.000f/PTM_RATIO,173.000f/PTM_RATIO );
	//		vertices[1].Set(31.000f/PTM_RATIO,173.000f/PTM_RATIO);
	//		vertices[2].Set( 38.000f/PTM_RATIO,37.000f/PTM_RATIO );
	//		vertices[3].Set( 50.000f/PTM_RATIO,52.000f/PTM_RATIO );
	//
	//		count = 4;
	//		shape.Set(vertices,count);
	//		//shape.SetAsBox(filledPolygon->getContentSize().width/PTM_RATIO/2,
	//		//		filledPolygon->getContentSize().height/PTM_RATIO/2);
	//
	//		blockShapeDef.shape = &shape;
	//		blockShapeDef.density = 1.0;
	//		blockShapeDef.friction = 0.0;
	//		blockShapeDef.restitution = 0.1f;
	//		blockBody2->CreateFixture(&blockShapeDef);
	//
	//
	//
	//		vertices[0].Set( 50.000f/PTM_RATIO,52.000f/PTM_RATIO );
	//		vertices[1].Set( 38.000f/PTM_RATIO,37.000f/PTM_RATIO );
	//		vertices[3].Set( 102.000f/PTM_RATIO,52.000f/PTM_RATIO );
	//		vertices[2].Set( 111.000f/PTM_RATIO,37.000f/PTM_RATIO );
	//
	//
	//
	//		count = 4;
	//		shape.Set(vertices,count);
	//		//shape.SetAsBox(filledPolygon->getContentSize().width/PTM_RATIO/2,
	//		//		filledPolygon->getContentSize().height/PTM_RATIO/2);
	//
	//		blockShapeDef.shape = &shape;
	//		blockShapeDef.density = 1.0;
	//		blockShapeDef.friction = 0.0;
	//		blockShapeDef.restitution = 1.0f;
	//		blockBody2->CreateFixture(&blockShapeDef);
	//
	//
	//		vertices[1].Set( 111.000f/PTM_RATIO,37.000f/PTM_RATIO );
	//		vertices[0].Set( 102.000f/PTM_RATIO,52.000f/PTM_RATIO );
	//		vertices[4].Set( 99.000f/PTM_RATIO,112.000f/PTM_RATIO );
	//		vertices[3].Set( 115.000f/PTM_RATIO,105.000f/PTM_RATIO );
	//		vertices[2].Set( 120.000f/PTM_RATIO,64.000f/PTM_RATIO );
	//
	//		count = 5;
	//		shape.Set(vertices,count);
	//		//shape.SetAsBox(filledPolygon->getContentSize().width/PTM_RATIO/2,
	//		//		filledPolygon->getContentSize().height/PTM_RATIO/2);
	//
	//		blockShapeDef.shape = &shape;
	//		blockShapeDef.density = 1.0;
	//		blockShapeDef.friction = 0.0;
	//		blockShapeDef.restitution = 0.1f;
	//		blockBody2->CreateFixture(&blockShapeDef);
	//
	//
	//
	//
	//		vertices[0].Set( 99.000f/PTM_RATIO,112.000f/PTM_RATIO );
	//		vertices[1].Set( 115.000f/PTM_RATIO,105.000f/PTM_RATIO );
	//		vertices[2].Set( 142.000f/PTM_RATIO,154.000f/PTM_RATIO );
	//		vertices[3].Set( 126.000f/PTM_RATIO,159.000f/PTM_RATIO );
	//		count = 4;
	//		shape.Set(vertices,count);
	//		//shape.SetAsBox(filledPolygon->getContentSize().width/PTM_RATIO/2,
	//		//		filledPolygon->getContentSize().height/PTM_RATIO/2);
	//
	//		blockShapeDef.shape = &shape;
	//		blockShapeDef.density = 1.0;
	//		blockShapeDef.friction = 0.0;
	//		blockShapeDef.restitution = 0.1f;
	//		blockBody2->CreateFixture(&blockShapeDef);
	//
	//
	//
	//		vertices[0].Set( 142.000f/PTM_RATIO,154.000f/PTM_RATIO );
	//		vertices[1].Set( 126.000f/PTM_RATIO,159.000f/PTM_RATIO );
	//		vertices[2].Set( 127.000f/PTM_RATIO,175.000f/PTM_RATIO );
	//		vertices[3].Set( 139.000f/PTM_RATIO,179.000f/PTM_RATIO );
	//
	//
	//		count = 4;
	//		shape.Set(vertices,count);
	//		//shape.SetAsBox(filledPolygon->getContentSize().width/PTM_RATIO/2,
	//		//		filledPolygon->getContentSize().height/PTM_RATIO/2);
	//
	//		blockShapeDef.shape = &shape;
	//		blockShapeDef.density = 1.0;
	//		blockShapeDef.friction = 0.0;
	//		blockShapeDef.restitution = 0.1f;
	//		blockBody2->CreateFixture(&blockShapeDef);
	//
	//
	//
	//
	//	}





	//addChild(B2DebugDrawLayer::create(_world, PTM_RATIO), 9999);

	_contactListener = new ContactListener();
	_world->SetContactListener(_contactListener);

	this->schedule(schedule_selector(GameScene::tick));
	//this->schedule(schedule_selector(GameScene::tick2), 0.1);

	/*
    CCLabelTTF* pLabel = CCLabelTTF::create("가나다", "Arial", 24);

    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);


   // CCMoveBy* act1 = CCMoveBy::create(5, ccp(100, 0));
   //    pSprite->runAction(CCRepeat::create(act1, 5));
       CCMoveTo* act1 = CCMoveTo::create(10.0f, ccp(300, 300));

          pSprite->runAction(CCEaseBounceIn::create(act1));
	 */

	return true;
}

void GameScene::tick2(float dt)
{
	if( _s1 == CHAR_FALLDOWN ) {
		_speed -= 600 * dt;
	}
	else {
		_speed -= 200 * dt;
		_speed2 -= 200 * dt;
		_speed2 -= 200 * dt;
	}
}

void GameScene::tick(float dt)
{
	//It is recommended that a fixed time step is used with Box2D for stability
	//of the simulation, however, we are using a variable time step here.
	//You need to make an informed choice, the following URL is useful
	//http://gafferongames.com/game-physics/fix-your-timestep/


	//#define CHAR_READY 			1
	//#define CHAR_READY_END		2
	//#define CHAR_RUN			3
	//#define CHAR_WALK			4
	//#define CHAR_BREATH			5
	//#define CHAR_BREATH_END		6
	//#define CHAR_FALLDOWN		7
	//#define CHAR_FALLDOWN_END	8





	int velocityIterations = 8;
	int positionIterations = 1;

	// Instruct the world to perform a single step of simulation. It is
	// generally best to keep the time step and iterations fixed.
	_world->Step(dt, velocityIterations, positionIterations);

	bool blockFound = false;

	if( _s1 == CHAR_FALLDOWN ) {
		_speed -= 600 * dt;
	}
	else {
		_speed -= 200 * dt;
		_speed2 -= 200 * dt;
		_speed3 -= 200 * dt;
	}


	_user->update(dt, _speed);
	_op->update(dt, _speed2);
	_op2->update(dt, _speed3);

	if(_speed < 0 ) _speed = 0;
	if(_speed2 < 0 ) _speed2 = 0;
	if(_speed3 < 0 ) _speed3 = 0;




	float speed = (int)(dt* _speed);
	float speed2 = (int)(dt* _speed2);
	float speed3 = (int)(dt* _speed3);


	char tmp[256];
	sprintf(tmp, "_speed : %f    speed : %f ", _speed, speed);

	_sp->setString(tmp);


	/*
	switch(_s1) {
	case CHAR_IDLE:
		break;
	case	CHAR_READY :
		if( !armature->getAnimation()->getIsPlaying() ) {
			_s1 = CHAR_READY_END;
		}
		break;
	case	CHAR_READY_END :
		_s1 = CHAR_IDLE;

		break;
	case	CHAR_RUN :

	case	CHAR_WALK :
		if( speed > 5 ) {
			armature->getAnimation()->setSpeedScale(speed / 5.0f);
		}else {
			armature->getAnimation()->setSpeedScale(speed / 2);
		}

		if( speed < 5.0f ) {
			if( strcmp(armature->getAnimation()->getCurrentMovementID().c_str(), "walk")  ) {

				armature->getAnimation()->play("walk");
				armature->getAnimation()->setSpeedScale(1.0f);
			}
		}else if ( speed > 7.0f ) {
			if( strcmp(armature->getAnimation()->getCurrentMovementID().c_str(), "run")  ) {
				armature->getAnimation()->play("run");
				armature->getAnimation()->setSpeedScale(1.0f);
			}
		}

		if( speed > 50.0f ) {
			if( rand() % 2 == 0 ) {
				speed = 0;
				_speed = 0;
				armature->getAnimation()->play("breath");
				armature->getAnimation()->setSpeedScale(1.0f);
				_s1 = CHAR_BREATH;

			}else {
				armature->getAnimation()->play("falldown2");
				armature->getAnimation()->setSpeedScale(1.0f);
				_s1 = CHAR_FALLDOWN;
				_speed -= 200;
			}
		}
		break;
	case	CHAR_BREATH :
		if( !armature->getAnimation()->getIsPlaying() ) {
			_s1 = CHAR_BREATH_END;
		}
		break;
	case	CHAR_BREATH_END :
		_s1 = CHAR_IDLE;
		break;
	case	CHAR_FALLDOWN :
		if( !armature->getAnimation()->getIsPlaying() ) {
			_s1 = CHAR_FALLDOWN_END;
		}
		break;
	case	CHAR_FALLDOWN_END :
		_s1 = CHAR_IDLE;
		break;

	case	CHAR_RUNJUMP :

		if( strcmp(armature->getAnimation()->getCurrentMovementID().c_str(), "run_jump")  ) {
			if( !armature->getAnimation()->getIsPlaying() ) {
				_s1 = CHAR_RUNJUMP_END;
				CCLOG("-----> RUN_JUMP END!");
				break;
			}
			armature->getAnimation()->play("run_jump");
			armature->getAnimation()->setSpeedScale(1.0f);
			CCLOG("-----> RUN_JUMP START!");
		}

		break;

	case	CHAR_RUNJUMP_END :
		CCLOG("-----> RUN_JUMP END??????????");
		_s1 = CHAR_RUN;
		break;

	}
	 */

	CCSprite *_bg1 = (CCSprite *)this->getChildByTag(5);
	CCSprite *_bg2 = (CCSprite *)this->getChildByTag(6);




	CCPoint bg1Pos = _bg1->getPosition();
	CCPoint bg2Pos = _bg2->getPosition();







	bg1Pos.x -= speed;
	bg2Pos.x -= speed;

	// move scrolling background back by one screen width to achieve "endless" scrolling
	if (bg1Pos.x < -(_bg1->getContentSize().width))
	{
		bg1Pos.x += _bg1->getContentSize().width;
		bg2Pos.x += _bg1->getContentSize().width;
	}

	// remove any inaccuracies by assigning only int values
	// (prevents floating point rounding errors accumulating over time)
	bg1Pos.x = (int)bg1Pos.x;
	bg2Pos.x = (int)bg2Pos.x;
	_bg1->setPosition( bg1Pos );
	_bg2->setPosition( bg2Pos );


	//float s = armature->getAnimation()->getSpeedScale();


	//	if( strcmp(armature->getAnimation()->getCurrentMovementID().c_str(), "ready")  )
	//	armature->getAnimation()->setSpeedScale(speed / 5.0f);


	//if( !armature->getAnimation()->getIsPlaying()){
	//	_speed = 0;
	//}

	/*
	if( strcmp(armature2->getAnimation()->getCurrentMovementID().c_str(), "ready")  )
		armature2->getAnimation()->setSpeedScale(speed2 / 5.0f);
	 */

	_dist += speed;
	_dist2 += speed2;
	_dist3 += speed3;


	_p1->setPositionX(_dist / 50);
	_p2->setPositionX(_dist2 / 50);
	_p3->setPositionX(_dist3 / 50);


	_op->armature->setPositionX(
				_user->armature->getPosition().x - (_dist - _dist2)
		);
	_op2->armature->setPositionX(
				_user->armature->getPosition().x - (_dist - _dist3)
		);



	//Iterate over the bodies in the physics world
	for (b2Body* b = _world->GetBodyList(); b; b = b->GetNext())
	{
		if (b->GetUserData() != NULL) {
			//Synchronize the AtlasSprites position and rotation with the corresponding body
			CCSprite* myActor = (CCSprite*)b->GetUserData();
			myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
			myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
			/*
			if (myActor->getTag() == 1) {
				static int maxSpeed = 10;

				b2Vec2 velocity = b->GetLinearVelocity();
				float32 speed = velocity.Length();

				if (speed > maxSpeed) {
					b->SetLinearDamping(0.5);
				} else if (speed < maxSpeed) {
					b->SetLinearDamipng(0.0);
				}

			}

			if (myActor->getTag() == 2) {
				blockFound = true;
			}
			 */
		}

	}

	std::vector<b2Body *>toDestroy;
	std::vector<MyContact>::iterator pos;
	for(pos = _contactListener->_contacts.begin();
			pos != _contactListener->_contacts.end(); ++pos) {
		MyContact contact = *pos;

		if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||
				(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture)) {


			b2Body *bodyA = contact.fixtureA->GetBody();
			b2Body *bodyB = contact.fixtureB->GetBody();
			//CCLOG("-----> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!");

			CCSprite *b = (CCSprite *)bodyA->GetUserData();
			//CCLOG("-----> 22222222222222222222222!");
			if( b != NULL ) {
				if( b->getTag() == 1) {
					//CCLOG("-----> aasdfasdfsadfs!");
					b2Vec2 force = b2Vec2(0, 0);
					//bodyA->SetLinearDamping(1);// ApplyLinearImpulse(force, force);


				}}

			//CCLOG("-----> bbbbbbbbbbbbbbbbbbbbbbbbbbbbb!");
			b = (CCSprite *)bodyB->GetUserData();
			if( b != NULL ) {
				if( b->getTag() == 1) {
					//CCLOG("-----> jkljkljlk!");
					b2Vec2 force = b2Vec2(0, 0);
					//bodyB->SetLinearVelocity(force);

				}
			}
		}


		b2Body *bodyA = contact.fixtureA->GetBody();
		b2Body *bodyB = contact.fixtureB->GetBody();
		if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
			CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
			CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();

			/*
	            //Sprite A = ball, Sprite B = Block
	            if (spriteA->getTag() == 1 && spriteB->getTag() == 2) {
	                if (std::find(toDestroy.begin(), toDestroy.end(), bodyB) == toDestroy.end()) {
	                    toDestroy.push_back(bodyB);
	                }
	            }

	            //Sprite A = block, Sprite B = ball
	            else if (spriteA->getTag() == 2 && spriteB->getTag() == 1) {
	                if (std::find(toDestroy.begin(), toDestroy.end(), bodyA) == toDestroy.end()) {
	                    toDestroy.push_back(bodyA);
	                }
	            }
			 */
			/*
			bodyA->SetType(b2_dynamicBody);
			bodyB->SetType(b2_dynamicBody);
			b2RopeJointDef jd;
			jd.bodyA=bodyA; //define bodies
			jd.bodyB=bodyB;
			jd.localAnchorA = b2Vec2(0,0); //define anchors
			jd.localAnchorB = b2Vec2(0,0);
			jd.maxLength= (bodyB->GetPosition() - bodyA->GetPosition()).Length(); //define max length of joint = current distance between bodies
			_world->CreateJoint(&jd);
			 */
		}
	}

	std::vector<b2Body *>::iterator pos2;
	for (pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
		b2Body *body = *pos2;
		if (body->GetUserData() != NULL) {
			CCSprite *sprite = (CCSprite *) body->GetUserData();
			this->removeChild(sprite, true);
		}
		_world->DestroyBody(body);
	}
	/*
    std::vector<b2Body *>toDestroy;
    std::vector<MyContact>::iterator pos;
    for(pos = _contactListener->_contacts.begin();
        pos != _contactListener->_contacts.end(); ++pos) {
        MyContact contact = *pos;

        if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||
            (contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture)) {
            GameOverScene *gameOverScene = GameOverScene::node();
            gameOverScene->getLayer()->getLabel()->setString("You Lose! :[");
            CCDirector::sharedDirector()->replaceScene(gameOverScene);
        }

        b2Body *bodyA = contact.fixtureA->GetBody();
        b2Body *bodyB = contact.fixtureB->GetBody();
        if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
            CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
            CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();

            // Sprite A = ball, Sprite B = Block
            if (spriteA->getTag() == 1 && spriteB->getTag() == 2) {
                if (std::find(toDestroy.begin(), toDestroy.end(), bodyB)
                    == toDestroy.end()) {
                    toDestroy.push_back(bodyB);
                }
            }
            // Sprite B = block, Sprite A = ball
            else if (spriteA->getTag() == 2 && spriteB->getTag() == 1) {
                if (std::find(toDestroy.begin(), toDestroy.end(), bodyA)
                    == toDestroy.end()) {
                    toDestroy.push_back(bodyA);
                }
            }
        }
    }

    std::vector<b2Body *>::iterator pos2;
    for(pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
        b2Body *body = *pos2;
        if (body->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *) body->GetUserData();
            this->removeChild(sprite, true);
        }
        _world->DestroyBody(body);
    }

    if (!blockFound)
    {
        GameOverScene *gameOverScene = GameOverScene::node();
        gameOverScene->getLayer()->getLabel()->setString("You Win!");
        CCDirector::sharedDirector()->replaceScene(gameOverScene);
    }

    if (toDestroy.size() > 0)
    {
        SimpleAudioEngine::sharedEngine()->playEffect("blip.caf");
    }
	 */
}

// cpp with cocos2d-x
void GameScene::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
	CCTouch* touch = (CCTouch*)( touches->anyObject() );
	CCPoint location = touch->getLocation();
	location = CCDirector::sharedDirector()->convertToGL(location);

	return;

	//#define CHAR_READY 			1
	//#define CHAR_READY_END		2
	//#define CHAR_RUN			3
	//#define CHAR_WALK			4
	//#define CHAR_BREATH			5
	//#define CHAR_BREATH_END		6
	//#define CHAR_FALLDOWN		7
	//#define CHAR_FALLDOWN_END	8

	//_user->sendTouch(1);

	switch( _user->status ) {

	case CHAR_RUN :
	case CHAR_WALK :
		_speed += 50;
		break;
	case CHAR_READY_END :
	case CHAR_BREATH_END :
	case CHAR_IDLE :
		_speed += 100;
		_user->status = CHAR_RUN_START;
		//armature->getAnimation()->play("run");
		// armature->setPosition(ccp(300,50));
		//armature->setScale(1.0f);
		//armature->getAnimation()->setSpeedScale(1.0f);

		break;
	}


	//	if(location.x > 500)
	//	_speed += 50;
	//else
	//	_speed2 += 50;


	for (b2Body* b = _world->GetBodyList(); b; b = b->GetNext())
	{
		if (b->GetUserData() != NULL) {
			//Synchronize the AtlasSprites position and rotation with the corresponding body
			CCSprite* myActor = (CCSprite*)b->GetUserData();
			if (myActor->getTag() == 1) {
				b2Vec2 force = b2Vec2(10, 10);

				//_speed += 50;
				if(location.x < b->GetPosition().x * PTM_RATIO) {
					force.x = -force.x;
					//	_speed -= 100;
				}
				b->ApplyLinearImpulse(force, b->GetPosition());
			}
			//CCLOG("-----> ccccccccccccccccccccccccccccccccc!");
		}

	}

	/*
    int i;
    // Choose one of the touches to work with
   CCTouch* touch = (CCTouch*)( touches->anyObject() );
    CCPoint location = touch->getLocation();
    location = CCDirector::sharedDirector()->convertToGL(location);

   // Set up initial location of projectile
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

    for( i = 0; i < 1000; i++) {
    CCSprite *projectile = CCSprite::create("CloseNormal.png",
        CCRectMake(0, 0, 20, 20));



    projectile->setPosition( ccp((int)rand()% (int)visibleSize.width, (int)rand() % (int)visibleSize.height ) );

    this->addChild(projectile);

    CCMoveBy* act1 = CCMoveBy::create(5, ccp(100, 0));
    projectile->runAction(CCRepeat::create(act1, 5));
    }

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

	   CCTouch* touch = (CCTouch*)( touches->anyObject() );
	    CCPoint location = touch->getLocation();
	    location = CCDirector::sharedDirector()->convertToGL(location);

	   CCSprite *projectile = CCSprite::create("CloseNormal.png",
	        CCRectMake(0, 0, 40, 40));

	    projectile->setPosition(ccp(location.x, location.y));
	    projectile->setTag(1);
	      this->addChild(projectile);


	      b2BodyDef ballBodyDef;
	         ballBodyDef.type = b2_dynamicBody;
	  //       ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
	         ballBodyDef.position.Set(location.x/PTM_RATIO, (winSize.height - location.y)/PTM_RATIO);
	         ballBodyDef.userData = projectile;

	         b2Body *ballBody = _world->CreateBody(&ballBodyDef);

	         // Create circle shape
	         b2CircleShape circle;
	         circle.m_radius = 26.0/PTM_RATIO;

	         // Create shape definition and add body
	         b2FixtureDef ballShapeDef;
	         ballShapeDef.shape = &circle;
	         ballShapeDef.density = 1.0f;
	         ballShapeDef.friction = 0.f;
	         ballShapeDef.restitution = 1.0f;
	         _ballFixture = ballBody->CreateFixture(&ballShapeDef);

	         b2Vec2 force = b2Vec2(10, 10);
	         ballBody->ApplyLinearImpulse(force, ballBodyDef.position);
	 */
}


void GameScene::runCharacter(CCObject* pSender)
{
	/*
	armature->getAnimation()->playByIndex(0);
	// armature->setPosition(ccp(300,50));
	//armature->setScale(1.0f);
	armature->getAnimation()->setSpeedScale(1.0f);


	armature2->getAnimation()->playByIndex(0);
	// armature->setPosition(ccp(300,50));
	//armature->setScale(1.0f);
	armature2->getAnimation()->setSpeedScale(1.0f);
	_speed = 100;
	_speed2 = 100;
	 */
	if( _s1 == CHAR_RUN ) {
		_s1 = CHAR_RUNJUMP;
		CCLOG("--->jump menu click");
	}
}

void GameScene::falldownCharacter(CCObject* pSender)
{

	/*
	armature->getAnimation()->playByIndex(3);
	   // armature->setPosition(ccp(300,50));
	    //armature->setScale(1.0f);
	    armature->getAnimation()->setSpeedScale(1.0f);
		armature2->getAnimation()->playByIndex(3);
		   // armature->setPosition(ccp(300,50));
		    //armature->setScale(1.0f);
		    armature2->getAnimation()->setSpeedScale(1.0f);
		    _speed = 100;
		    _speed2 = 100;
	 */
	armature->getBone("Layer54")->changeDisplayByIndex(2, true);


}
void GameScene::falldownpreCharacter(CCObject* pSender)
{

	/*
	armature->getAnimation()->playByIndex(4);
	   // armature->setPosition(ccp(300,50));
	    //armature->setScale(1.0f);
	    armature->getAnimation()->setSpeedScale(1.0f);

		armature2->getAnimation()->playByIndex(4);
		   // armature->setPosition(ccp(300,50));
		    //armature->setScale(1.0f);
		    armature2->getAnimation()->setSpeedScale(1.0f);

	    _speed = 0;

	 */

	armature->getBone("Layer54")->changeDisplayByIndex(0, true);


}


void GameScene::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
	CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
#endif
}
